<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="handleInput" />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          :data="depts"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          @current-change="currentChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{row}">
              <span>{{ row.formOfEmployment===1?'正式':row.formOfEmployment===2?'非正式':'无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" style="margin-right:10px" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确定删除该员工吗？"
                @onConfirm="delEmployee(row)"
              >
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>

        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" style="height:60px" align="middle">
          <el-pagination
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            layout="total, prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @uptadeSuccess="getEmployeeList" />
    <!-- 角色dialog -->
    <!--
      el-checkbox-group v-model 选中/勾选的角色列表 []
      el-check 多个复选框 通过label可以收集选中的角色
     -->
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox
          v-for="item in enableRoleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="btnRoleConfirm">确认</el-button>
            <el-button size="mini" @click="showRoleDialog=false">取消</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { assignRoles, delEmployee, exportExcel, getEmployeeDetail, getEmployeeList } from '@/api/employee'
import { translateListToTreeData } from '@/utils'
import ImportExcel from './componets/import-excel.vue'
import FileSaver from 'file-saver'
import { getEnableRoleList } from '@/api/role'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      currentRoleId: null, // 当前选中的角色id
      showRoleDialog: false, // 分配角色的弹层
      showExcelDialog: false, // excel表格表单的弹层
      roleIds: [], // 选中的角色列表
      enableRoleList: [], // 已启用的角色列表
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 角色列表
      list: [],
      queryParams: {
        departmentId: null, // 部门id
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      total: 0
    }
  },
  async  created() {
    const res = await getDepartmentList()
    // 处理数据
    this.depts = translateListToTreeData(res, 0)
    this.queryParams.departmentId = this.depts[0].id
    // 首次加载获取角色列表
    this.getEmployeeList()
    // 渲染是异步的 - 等待机制
    this.$nextTick(() => {
      this.$refs.tree.setCurrentKey(this.queryParams.departmentId)
    })
  },
  methods: {
    // 点击角色按钮
    async  btnRole(id) {
      this.currentRoleId = id
      // 1. 角色列表赋值
      this.enableRoleList = await getEnableRoleList()
      // 2. 显示该用户拥有的角色信息
      const { roleIds } = await getEmployeeDetail(id)
      // 3. 回显角色选中信息
      this.roleIds = roleIds
      // 4. 显示弹出层 - 先渲染-再展示弹层
      this.showRoleDialog = true
    },
    // 分配权限点击确认按钮
    async btnRoleConfirm() {
      // 1. 调用分配角色的接口
      await assignRoles({ id: this.currentRoleId, roleIds: this.roleIds })
      // 2. 提示用户
      this.$message.success('分配角色成功')
      // 3. 关闭弹层
      this.showRoleDialog = false
    },
    // 删除角色
    async   delEmployee(row) {
      await delEmployee(row.id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
    },
    // excel文件的导出
    async  exportExcel() {
      // res -> blob对象 二进制数据
      const res = await exportExcel()
      // FileSaver.saveAs(blob对象, 文件名.xlsx)
      FileSaver.saveAs(res, '员工测试表.xlsx')
    },
    // 左边树形图节点的切换
    currentChange(node) {
      // node 当前选中节点的信息 - 对象
      this.queryParams.departmentId = node.id
      // 重新设置页码 - 第一页
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    // 右表数据获取
    async  getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    // 切换分页事件
    handleCurrentChange(value) {
      this.queryParams.page = value
      this.getEmployeeList()
    },
    // 搜索框事件
    handleInput() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // 页码重置 - 第一页
        this.queryParams.page = 1
        // 查询员工的列表
        this.getEmployeeList()
      }, 800)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
